package com.sui.bigdata.sml.web.service.impl;

import com.sui.bigdata.sml.web.dto.ExperimentDTO;
import com.sui.bigdata.sml.web.dto.ProjectDTO;
import com.sui.bigdata.sml.web.exception.EntityNotFoundException;
import com.sui.bigdata.sml.web.repository.mapper.ExperimentMapper;
import com.sui.bigdata.sml.web.repository.model.Experiment;
import com.sui.bigdata.sml.web.service.ExperimentService;
import com.sui.bigdata.sml.web.util.Constants;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songhaicheng
 * @date 2019/11/6 11:27
 * @description
 * @reviewer
 */
@Service
@DependsOn("disconfConfig")
@Slf4j
public class ExperimentServiceImpl implements ExperimentService {

    @Autowired
    private ExperimentMapper mapper;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public Long add(ExperimentDTO dto) {
        Experiment experiment = mapperFacade.map(dto, Experiment.class);
        // 给 userId 占位
        experiment.setUserId(Constants.DEFAULT_USER_ID);
        // 同项目下不能存在有同名且未被删除的实验
        if (mapper.listByProjectId(dto.getProjectId(), false).stream().anyMatch(e -> e.getName().equals(dto.getName()))) {
            throw new RuntimeException("已存在同名实验：" + dto.getName());
        }
        mapper.insert(experiment);
        return experiment.getId();
    }

    @Override
    public ExperimentDTO get(Long id) {
        Experiment experiment = mapper.get(id);
        if (experiment == null || experiment.getDelete()) {
            throw new EntityNotFoundException(Experiment.class, id);
        }
        return mapperFacade.map(experiment, ExperimentDTO.class);
    }

    @Override
    public Boolean update(ExperimentDTO dto) {
        get(dto.getId());
        Experiment experiment = mapperFacade.map(dto, Experiment.class);
        return mapper.update(experiment) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        // 删除实验不真正删除数据库，只改变删除字段标记位
        Experiment experiment = mapperFacade.map(get(id), Experiment.class);
        experiment.setDelete(true);
        return mapper.update(experiment) == 1;
    }

    @Override
    public List<ExperimentDTO> listByProject(ProjectDTO projectDto, Boolean delete) {
        return mapperFacade.mapAsList(mapper.listByProjectId(projectDto.getId(), delete), ExperimentDTO.class);
    }

}
